
//
//  ZStoreSubViewController.m
//  ZQLearn
//
//  Created by macfeel on 2019/4/23.
//  Copyright © 2019 macfeel. All rights reserved.
//

#import "ZStoreSubViewController.h"
#import "StoreCollectionViewCell.h"
#import "ZStoreDetailViewController.h"
#import "SDCycleScrollView.h"
#import "BannerModel.h"
#import "StoreModel.h"
@interface ZStoreSubViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong)UICollectionView *collectionView;

@property (nonatomic,strong)SDCycleScrollView *cycleView;

@property(nonatomic,copy)NSString *indexId;
@property (nonatomic,strong)NSMutableArray *bannerArray;
@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong)NSMutableArray *urlArray;

@property(nonatomic,assign)NSInteger currentPage;



@end

#define kLineNumber 3
#define kBarHeight 40

///这个cellid 全局不能重复  所以建议写成宏的形式，而不是这种全局常量的形式
//NSString *const cellid = @"store";

#define cellIdentifier @"store"


@implementation ZStoreSubViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //    self.currentIndex = -1;
    self.currentPage = 1;
    self.bannerArray = [NSMutableArray array];
    self.dataArray = [NSMutableArray array];
    self.urlArray = [NSMutableArray array];
    [self.view addSubview:self.collectionView];
    //    [self addBannerView];
    //    [self loadBanner];
    // Do any additional setup after loading the view.
}

- (void)endRefresh{
    [self.collectionView.mj_header endRefreshing];
    [self.collectionView.mj_footer endRefreshing];
}

//流式布局
- (UICollectionViewFlowLayout *)flowLayout {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //整个 section 的四周边界的margin
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    ///45行代码和  ScreenWidth-4（minimumLineSpacing*2）形成中间的小横线
    layout.minimumLineSpacing = 2.f;
    layout.minimumInteritemSpacing = 0.f;
    //    layout.headerReferenceSize = CGSizeMake(kScreenWidth, SectionHeaderHeight);
    layout.itemSize = CGSizeMake((ScreenWidth-4)/3, 170);
    return layout;
}
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-TabBarHeight-NavBarHeight-kBarHeight-175) collectionViewLayout:[self flowLayout]];
        
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        [self registerCell];
        WeakStament(ws);
        _collectionView.mj_header = [CustomRefreshHeader headerWithRefreshingBlock:^{
            [ws endRefresh];
        }];
        _collectionView.backgroundColor = kWhiteColor;
    }
    return _collectionView;
}

- (void)registerCell {
    
    [_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([StoreCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:cellIdentifier];
    
    //最后一个有一个尾视图  到时候需要用到
    //    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headReuseID];
    
}



#pragma datasource
//-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
//    return 1;
//}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    //    if (self.currentIndex == 0) {
    //        return 3;
    //    }
    //    return 1;
    return self.dataArray.count;
}



-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    StoreModel *model = self.dataArray[indexPath.row];
    StoreCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    [cell.headImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kStorePicServerUrl,model.photo]] placeholderImage:nil];
    YYLog(@"%@%@",kStorePicServerUrl,model.photo);
    YYLog(@"%@%@",kPicServerUrl,model.photo);
    cell.nameLab.text = model.name;
    cell.scoreLab.text = [NSString stringWithFormat:@"%@积分",model.integral];
    return cell;
    
}


#pragma mark - delegate
//cell尺寸
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//
//    CGFloat width=ScreenWidth/kLineNumber;
//    return CGSizeMake(width, width*1.2);
//}

///section header 尺寸
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
//    return CGSizeMake(ScreenWidth, SectionHeaderHeight-20);
//}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    StoreModel *model = self.dataArray[indexPath.row];
    
    ZStoreDetailViewController *detail = [ZStoreDetailViewController new];
    
    detail.cid = model.ID;
    detail.urlArr = [self.urlArray copy];
    detail.model = model;
    [self.navigationController pushViewController:detail animated:YES];
    
}

#pragma mark ZJScrollPageViewChildVcDelegate
- (void)zj_viewWillAppearForIndex:(NSInteger)index{
    YYLog(@"%ld",index);
    //    [UserModel shareInstance].tabIndex = index;
    //    self.currentIndexId = index;
}
- (void)zj_viewDidAppearForIndex:(NSInteger)index{
    
}
- (void)zj_viewWillDisappearForIndex:(NSInteger)index{
    
}
- (void)zj_viewDidDisappearForIndex:(NSInteger)index{
    
}
- (void)zj_viewDidLoadForIndex:(NSInteger)index{
    //这里具体处理请求逻辑不同的页面根据索引进行请求
    YYLog(@"%ld",index);
    //    self.currentIndex = index;
    if (self.datas.count>0) {
        
        StoreModel *model = self.datas[index];
        self.indexId = model.ID ;
        [self loadDataWithId:model.ID];
        YYLog(@"%@",model.ID);
        
    }
}

- (void)refreshData{
    self.currentPage=1;
    //    self.currentIndexId = [UserModel shareInstance].Id;
    [self loadDataWithId:self.indexId];
}

- (void)loadDataWithId:(NSString *)Id{
    if (self.currentPage==1) {
        [self.dataArray removeAllObjects];
    }
    NSDictionary *dic = @{@"commodityClass.id":Id,@"pageSize":@(20),@"pageIndex":@(1)};
    WeakStament(ws);
    [ZNetworkService postRequestWithBaseUrl:kStoreListUrl setParameters:dic success:^(id result) {
        
        YYLog(@"%@",result);
        if ([result[@"errorCode"]integerValue]==0) {
            NSArray *arr = result[@"result"];
            for (NSDictionary *dc in arr) {
                StoreModel *model = [StoreModel mj_objectWithKeyValues:dc];
                [ws.dataArray addObject:model];
                
                ///从字符包数组中进行截取，然后再拼上图片服务器前缀
                NSString *pho = [model.bannerPhoto substringWithRange:NSMakeRange(2, 21)];
                NSString *url = [NSString stringWithFormat:@"%@%@",kStorePicServerUrl,pho];
                YYLog(@"%@",url);
                //图片url数组
                [self.urlArray addObject:url];
                ///后台返回的数据正常应该是个数组，但是返回的是一个字符串包起来的数组
//                [ws setAllPhotos:model.bannerPhoto];
            }
            [ws.collectionView reloadData];
            [ws endRefresh];
        }else{
            [AFToast showText:result[@"errorMsg"]];
            [ws endRefresh];
        }
        
        
    } fail:^(NSError *error) {
        YYLog(@"%@",error);
        [self endRefresh];
        
    } delegater:nil];
}

////将照片都加上前缀
-(void)setAllPhotos:(NSArray *)arr{
    for (NSString *photo in arr) {
        NSString *purl = [NSString stringWithFormat:@"%@%@",kStorePicServerUrl,photo];
        YYLog(@"%@",purl);
        [self.urlArray addObject:purl];
    }
}




@end
